/**
 * 项目版本批量删除接口测试用例
 *
 * Created by snowingsea on 2020/02/13.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));

const common = require('./../../common');
const Administrator = require('./../../../models/administrator');
const uri = require('./../uri');
const { statusKind } = require('./../../../../phoenix/models/project-versions');

module.exports = describe('/DELETE projects/:id/versions.json', function () {
  const administrator = new Administrator();
  let project;
  const newUserIds = [];
  function url(projectId) {
    if (!projectId) {
      projectId = project.projectId;
    }
    return `/projects/${projectId}/versions.json`;
  }

  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((res) => {
        project = res;
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'delete');
  common.should.be.tester(uri, url, 'delete');

  // 正常删除
  it('it should DELETE project versions', function (done) {
    let orgVersionTotalNumber;
    let newVersions;
    let allVersionTotalNumber;
    const newVersionCount = 10;
    const otherProjects = [];
    const otherProjectVersionCount = 3;
    administrator.createRandomTester()
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((project) => {
        otherProjects.push(project);
        return project.createRandomVersions(otherProjectVersionCount);
      })
      .then(() => project.creator.createRandomProject())
      .then((project) => {
        otherProjects.push(project);
        return project.createRandomVersions(otherProjectVersionCount);
      })
      .then(() => project.createRandomVersions(Math.floor(Math.random() * 5)))
      .then(() => project.getVersionTotalNumber())
      .then((totalNumber) => {
        orgVersionTotalNumber = totalNumber;
        return project.createRandomVersions(newVersionCount);
      })
      .then((versions) => {
        newVersions = versions;
        return project.getVersionTotalNumber();
      })
      .then((totalNumber) => {
        allVersionTotalNumber = totalNumber;
        return project.creator.login();
      })
      .then(() => {
        chai.request(uri)
          .delete(url())
          .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
          .query({ versionIds: newVersions.map(({ versionId }) => versionId) })
          .end((err, res) => {
            res.should.have.status(204);

            project.getVersionTotalNumber()
              .then((totalNumber) => {
                allVersionTotalNumber.should.be.eql(orgVersionTotalNumber + newVersionCount);
                totalNumber.should.be.eql(orgVersionTotalNumber);
                const promises = otherProjects.map((project) => project.getVersionTotalNumber());
                return Promise.all(promises);
              })
              .then((totalNumbers) => {
                totalNumbers.forEach((totalNumber) => {
                  totalNumber.should.be.eql(otherProjectVersionCount + 1);
                });
                done();
              })
              .catch(done);
          });
      })
      .catch(done);
  });

  // 反选删除
  it('it should delete project versions except original versions', function (done) {
    let exceptVersions;
    const otherProjects = [];
    const otherProjectVersionCount = 3;
    administrator.createRandomTester()
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((project) => {
        otherProjects.push(project);
        return project.createRandomVersions(otherProjectVersionCount);
      })
      .then(() => project.creator.createRandomProject())
      .then((project) => {
        otherProjects.push(project);
        return project.createRandomVersions(otherProjectVersionCount);
      })
      .then(() => project.createRandomVersions(Math.floor(Math.random() * 5) + 1))
      .then((versions) => {
        exceptVersions = versions;
        return project.createRandomVersions();
      })
      .then(() => project.creator.login())
      .then(() => {
        chai.request(uri)
          .delete(url())
          .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
          .query({ exceptVersionIds: exceptVersions.map(({ versionId }) => versionId) })
          .end((err, res) => {
            res.should.have.status(204);

            project.getVersionTotalNumber()
              .then((totalNumber) => {
                totalNumber.should.be.eql(exceptVersions.length);

                const promises = otherProjects.map((project) => project.getVersionTotalNumber());
                return Promise.all(promises);
              })
              .then((totalNumbers) => {
                totalNumbers.forEach((totalNumber) => {
                  totalNumber.should.be.eql(otherProjectVersionCount + 1);
                });
                done();
              })
              .catch(done);
          });
      })
      .catch(done);
  });

  // 删除某项目的所有版本
  it('it should delete all versions of a project', function (done) {
    let newProject;
    const otherProjects = [];
    const otherProjectVersionCount = 3;
    administrator.createRandomTester()
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((project) => {
        otherProjects.push(project);
        return project.createRandomVersions(otherProjectVersionCount);
      })
      .then(() => project.creator.createRandomProject())
      .then((project) => {
        otherProjects.push(project);
        return project.createRandomVersions(otherProjectVersionCount);
      })
      .then(() => project.creator.createRandomProject())
      .then((project) => {
        newProject = project;
        return newProject.createRandomVersions();
      })
      .then(() => project.creator.login())
      .then(() => {
        chai.request(uri)
          .delete(url(newProject.projectId))
          .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
          .query({ exceptVersionIds: [] })
          .end((err, res) => {
            res.should.have.status(204);

            // 查询项目
            chai.request(uri)
              .get(`/projects/${newProject.projectId}.json`)
              .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
              .end((err, res) => {
                res.should.have.status(200);
                common.should.be.projectMessage(res.body);
                res.body.should.not.have.property('lastVersion');

                const promises = otherProjects.map((project) => project.getVersionTotalNumber());
                Promise.all(promises)
                  .then((totalNumbers) => {
                    totalNumbers.forEach((totalNumber) => {
                      totalNumber.should.be.eql(otherProjectVersionCount + 1);
                    });
                    done();
                  })
                  .catch(done);
              });
          });
      })
      .catch(done);
  });

  // 删除冻结版本
  it('it should delete frozen project versions except one', function (done) {
    const exceptVersionIds = [];
    let normalVersionCount;
    project.createRandomVersion()
      .then(({ versionId }) => {
        exceptVersionIds.push(versionId);
        return project.freezeVersion(versionId);
      })
      .then(() => project.createRandomVersions())
      .then((versions) => project.randomFreezeVersions(versions))
      .then(() => project.getVersionTotalNumber({ status: statusKind.normal }))
      .then((number) => {
        normalVersionCount = number;
        return project.creator.login();
      })
      .then(() => {
        chai.request(uri)
          .delete(url())
          .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
          .query({ exceptVersionIds, status: [statusKind.frozen] })
          .end((err, res) => {
            res.should.have.status(204);
            project.getVersionTotalNumber()
              .then((totalNumber) => {
                totalNumber.should.be.eql(normalVersionCount + 1);
                done();
              })
              .catch(done);
          });
      })
      .catch(done);
  });

  // 删除不存在项目中的版本
  it('it should fail to delete project versions when the project is not exists', function (done) {
    let projectId;
    project.creator.createRandomProject()
      .then((res) => {
        projectId = res.projectId;
        return res.createRandomVersions(Math.floor(Math.random() * 5) + 1);
      })
      .then(() => project.creator.removeProject(projectId))
      .then(() => project.creator.login())
      .then(() => {
        chai.request(uri)
          .delete(url(projectId))
          .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      });
  });

  // 不可删除他人的项目版本
  it('it should fail to delete project versions when the project is not yours', function (done) {
    let otherProjectId;
    administrator.createRandomTester()
      .then((newTester) => {
        newUserIds.push(newTester.userId);
        return newTester.createRandomProject();
      })
      .then((project) => {
        otherProjectId = project.projectId;
        return project.createRandomVersions(Math.floor(Math.random() * 5) + 1);
      })
      .then(() => project.creator.login())
      .then(() => {
        chai.request(uri)
          .delete(url(otherProjectId))
          .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 冻结的项目不可删除版本
  it('it should fail to delete project versions when the project is frozen', function (done) {
    let newProjectId;
    project.creator.createRandomProject()
      .then((project) => {
        newProjectId = project.projectId;
        return project.createRandomVersions(Math.floor(Math.random() * 5) + 1);
      })
      .then(() => project.creator.freezeProject(newProjectId))
      .then(() => project.creator.login())
      .then(() => {
        chai.request(uri)
          .delete(url(newProjectId))
          .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(403);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });
});
